package cn.hsa.fqz.task.service.impl;


import cn.hsa.fqz.common.enums.IncidentsResultEnum;
import cn.hsa.fqz.common.enums.ProcessStatusEnum;
import cn.hsa.fqz.common.utils.EntityCopyUtil;
import cn.hsa.fqz.task.dao.TTaskFeedbackMapper;
import cn.hsa.fqz.task.dao.TTaskMapper;
import cn.hsa.fqz.task.dao.TTaskProcessMapper;
import cn.hsa.fqz.task.entity.TTask;
import cn.hsa.fqz.task.entity.TTaskFeedback;
import cn.hsa.fqz.task.entity.TTaskProcess;
import cn.hsa.fqz.task.service.ITaskFeedbackService;
import cn.hsa.fqz.task.service.dto.AddTaskFeedbackDTO;
import cn.hsa.fqz.task.service.dto.LoginUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 丁志敏
 * @version v1.0
 * @apiNote 功能描述:()
 * @date create in 2022/9/15 11:09
 */
@Slf4j
@Service
public class TaskFeedbackServiceImpl implements ITaskFeedbackService {

    @Autowired
    private TTaskFeedbackMapper tTaskFeedbackMapper;
    @Autowired
    private TTaskMapper tTaskMapper;
    @Autowired
    private TTaskProcessMapper tTaskProcessMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(LoginUserDTO loginUser, AddTaskFeedbackDTO create) {
        TTaskFeedback feedback = EntityCopyUtil.copy(create,TTaskFeedback.class);
        TTask tTask = tTaskMapper.selectByPrimaryKey(feedback.getTaskId());
        TTask subTask = tTaskMapper.selectByPrimaryKey(feedback.getSubTaskId());
        subTask.setResult(IncidentsResultEnum.FINISHED.name());
        tTaskMapper.updateByPrimaryKeySelective(subTask);

        TTaskProcess process = new TTaskProcess();
        process.setTitle(tTask.getTitle());
        process.setFrom(tTask.getSendBy());
        process.setTo(loginUser.getRegion());
        process.setTaskId(tTask.getId());
        process.setMemo(ProcessStatusEnum.FINISHED.getLabel());
        process.setOccurDate(new Date());
        process.setOperation(ProcessStatusEnum.FINISHED.getLabel());

        tTaskProcessMapper.insert(process);

        feedback.setCreateBy(loginUser.getUid());
        feedback.setCreateTime(new Date());
        return tTaskFeedbackMapper.insertSelective(feedback) > 0;
    }

    @Override
    public List<TTaskFeedback> list(Integer taskId) {
        TTask task = tTaskMapper.selectByPrimaryKey(taskId);
        List<TTaskFeedback> list = null;
        if(task.getIsParent() == 1){
            list = tTaskFeedbackMapper.selectByParentTaskId(taskId);
        }else{
            list = tTaskFeedbackMapper.selectBySubTaskId(taskId);
        }
        return list;
    }

    @Override
    public TTaskFeedback detail(Integer feedbackId) {
        return tTaskFeedbackMapper.selectByPrimaryKey(feedbackId);
    }

}
